<template>
  <div class="main-container">
    <a-card class="layout-card">
      <a-row align="middle" justify="space-between">
        <SearchGroup
          :label-option="labelOption"
          @handleSearch="loadData(1)"
          @handleReset="reset"
          :searchOption="filterOption"
        />
        <a-col>
          <a-button class="btn" type="primary" @click="handlOpen()">
            <plus-outlined />新建管理账号
          </a-button>
        </a-col>
      </a-row>
      <a-table
        bordered
        rowKey="account"
        :pagination="false"
        :scroll="{ x: 1450 }"
        class="tablstyle"
        :dataSource="list"
        :columns="columns"
      >
        <template #bodyCell="{ record, column, index }">
          <template v-if="column.key === 'index'">
            <span>{{ index + 1 }}</span>
          </template>
          <template v-if="column.key === 'xyRelationInfoVOList'">
            <a-tag v-for="item in record.xyRelationInfoVOList" :key="item.autoId">{{
              item.xymc
            }}</a-tag>
          </template>
          <template v-if="column.key === 'operation'">
            <a-button
              type="link"
              :disabled="record.accountType != 'MANAGE'"
              @click="openCollege(record)"
            >
              分配学院
            </a-button>
            <a-button
              type="link"
              :disabled="record.accountType == 'ADMIN'"
              @click="handlOpen(record)"
            >
              编辑
            </a-button>
            <a-popconfirm
              :title="record.accountState == 'NORMAL' ? '确认禁用吗?' : '确认启用吗?'"
              @confirm="conclose(record)"
            >
              <a-button
                type="link"
                :disabled="record.accountType == 'ADMIN' && record.accountState == 'NORMAL'"
                :danger="record.accountState == 'NORMAL'"
              >
                {{ record.accountState == 'NORMAL' ? '禁用' : '启用' }}
              </a-button>
            </a-popconfirm>
            <a-button
              type="link"
              :disabled="record.accountType == 'ADMIN'"
              danger
              @click="handelDelete(record.account)"
              >删除</a-button
            >
            <a-button
              type="link"
              :disabled="record.accountType == 'ADMIN'"
              @click="handlSetPwd(record)"
            >
              修改密码
            </a-button>
            <a-button
              type="link"
              :disabled="record.accountType == 'ADMIN'"
              @click="handlSetRole(record)"
            >
              设置角色
            </a-button>
          </template>
        </template>
      </a-table>
      <a-pagination
        :show-total="total => `共 ${total} 条`"
        :show-size-changer="false"
        show-quick-jumper
        v-model:current="curPage"
        v-model:pageSize="pageSize"
        :total="total"
      />
    </a-card>

    <a-modal
      class="loading"
      :visible="addModalVisible"
      width="25%"
      :title="titlePop"
      @cancel="handleClose"
      @ok="handleOk"
    >
      <a-form class="form" :model="formStore" :rules="rules">
        <a-form-item label="教师姓名" name="jsxm">
          <a-input v-model:value="formStore.jsxm" placeholder="请输入教师姓名" />
        </a-form-item>
        <a-form-item label="登录账号" name="account">
          <a-input
            v-model:value="formStore.account"
            :disabled="titlePop === '编辑管理员账号'"
            placeholder="请输入登录账号"
          />
        </a-form-item>
        <a-form-item label="账号类型" name="accountType">
          <a-select
            :disabled="formStore.autoId"
            width="100%"
            v-model:value="formStore.accountType"
            :options="accountTypOption"
            placeholder="请选择账号类型"
          />
        </a-form-item>
        <a-form-item
          label="管理学院"
          name="xydm"
          v-if="formStore.accountType == 'XY' && titlePop === '新增管理员账号'"
        >
          <a-select
            allowClear
            v-model:value="formStore.xydm"
            :options="collegeList"
            placeholder="请选择学院"
            show-search
            :filter-option="selectFilterOption"
          >
            <template #suffixIcon>
              <caret-down-outlined class="ant-select-suffix" />
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="设置密码" name="pwd" v-if="!formStore.autoId">
          <a-input v-model:value="formStore.pwd" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="重复密码" name="pwdTwo" v-if="!formStore.autoId">
          <a-input v-model:value="formStore.pwdTwo" placeholder="请输入密码" />
        </a-form-item>
      </a-form>
    </a-modal>

    <undatePasword v-model:setModalVisible="setModalVisible" v-model:account="formManagAccount" />

    <roleModal v-model:roleModalVisible="roleModalVisible" v-model:account="formManagAccount" />

    <assignMent v-model:visible="addManageVisible" v-model:account="formManagAccount" />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'

import assignMent from './assignment.vue'
import roleModal from './roleModal.vue'
import undatePasword from './undatePasword.vue'

import { delConfirm } from '/@/hooks/web/useCommonMessage'
import { useMessage } from '/@/hooks/web/useMessage'
import { cloneDeep } from 'lodash-es'
import {
  deleteByIds,
  getManageTeacherCard,
  setPipeStatus,
  addTeacher,
} from '/@/api/system-manage/teacher-info'
import { getCollegeList } from '/@/api/organization/collegeManage'
import { message } from 'ant-design-vue'
import { isArray } from '/@/utils/is'
import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const userInfo = computed<any>(() => userStore.getUserInfo)
const { createMessage } = useMessage()
const formStore = ref<any>({})

import { useList } from '/@/hooks/web/useList'

const labelOption = ref<any>([
  { name: '登录账号', key: 'account', inputWidth: 150, labelWidth: 70 },
  { name: '账号类型', key: 'accountType', inputWidth: 150, labelWidth: 70, selectOption: [] },
  {
    name: '账号状态',
    key: 'accountState',
    selectOption: [],
    inputWidth: 150,
    labelWidth: 70,
  },
])

// 列表数据
const { reset, loadData, filterOption, curPage, total, pageSize, list } =
  useList(getManageTeacherCard)

const rules = {
  todoValueList: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
}

const addModalVisible = ref(false)

const columns = ref([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    width: '80px',
    fixed: true,
  },
  {
    title: '登录账号',
    dataIndex: 'account',
    key: 'account',
    align: 'center',
  },
  {
    title: '教师姓名',
    dataIndex: 'jsxm',
    key: 'jsxm',
    align: 'center',
  },
  {
    title: '账号状态',
    dataIndex: 'accountState',
    key: 'accountState',
    align: 'center',
    customRender: params => {
      if (!isArray(labelOption.value[2].selectOption)) return '--'
      let arr = labelOption.value[2].selectOption.filter(e => e.dictCode == params.value)
      if (arr.length) return arr[0].dictName
      return '--'
    },
  },
  {
    title: '账号类型',
    dataIndex: 'accountType',
    key: 'accountType',
    align: 'center',
    customRender: params => {
      if (!isArray(labelOption.value[1].selectOption)) return '--'
      let arr = labelOption.value[1].selectOption.filter(e => e.dictCode == params.value)
      if (arr.length) return arr[0].dictName
      return '--'
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    align: 'center',
    width: '270px',
    fixed: 'right',
  },
])

// 修改状态
const conclose = async record => {
  try {
    let { code, message } = await setPipeStatus({
      account: record.account,
      operateState: record.accountState == 'BAN',
    })
    if (code == 200) {
      record.accountState = record.accountState == 'BAN' ? 'NORMAL' : 'BAN'
    } else {
      createMessage.error(message)
    }
  } catch (err) {
    console.log(err)
  }
}

const handleClose = () => {
  formStore.value = cloneDeep({})
  addModalVisible.value = false
}

const handleOk = async () => {
  if (!formStore.value.autoId) {
    formStore.value.accountState = 'NORMAL' //默认启用账号
    if (formStore.value.pwd != formStore.value.pwdTwo) {
      return message.error('密码不一致')
    }
  }
  addTeacher({
    ...formStore.value,
    manageXydm: formStore.value.accountType == 'XY' ? formStore.value.xydm : '',
  }).then(res => {
    if (res.code == 200) {
      message.success('操作成功')
      loadData()
      handleClose()
    } else {
      message.error(res.message)
    }
  })
}
// 新增编辑账号弹窗开启
const titlePop = ref('')
const handlOpen = async (record: any = {}) => {
  formStore.value = cloneDeep(record)
  titlePop.value = formStore.value.account ? '编辑管理员账号' : '新增管理员账号'
  addModalVisible.value = true
}

// 修改密码
const setModalVisible = ref(false)
const handlSetPwd = async record => {
  formManagAccount.value = record.account
  setModalVisible.value = true
}

// 分配角色 （待完成）
const roleModalVisible = ref(false)
const handlSetRole = async record => {
  formManagAccount.value = record.account
  roleModalVisible.value = true
}

// 学院管理
const addManageVisible = ref(false)
const formManagAccount = ref<any>('')
const openCollege = async record => {
  formManagAccount.value = record.account
  addManageVisible.value = true
}

// 删除账号
const handelDelete = account => {
  delConfirm(deleteByIds, { account }, loadData)
}

import { getDictionaryList } from '/@/views/teacher/home/index'

const accountTypOption = ref([])

// 学院列表
const collegeList = ref<any>([])
const getCollegeOption = async () => {
  try {
    const { data } = await getCollegeList({
      pageNum: 0,
      pageSize: 9999,
    })
    data.forEach(ele => {
      ele.codeName = `${ele.xydm}(${ele.xymc})`
      ele.value = ele.xydm
      ele.label = ele.codeName
    })
    collegeList.value = data.sort((a, b) => a.xydm - b.xydm)
  } catch (error) {
    console.log(error)
  }
}

// 筛选学院列表选项
const selectFilterOption = (input: string, option: any) => {
  return option.codeName.includes(input)
}

onMounted(async () => {
  labelOption.value[2].selectOption = await getDictionaryList('state')
  labelOption.value[1].selectOption = await getDictionaryList('accountType')

  labelOption.value[1].selectOption = labelOption.value[1].selectOption.filter(
    el => el.dictCode != 'PYJS'
  )

  accountTypOption.value = labelOption.value[1].selectOption.filter(el => {
    el.disabled = userInfo.value.accountType != 'ADMIN'
    return el.dictCode == 'MANAGE' || el.dictCode == 'XY'
  })
  getCollegeOption()
})
</script>
<style lang="less" scoped>
.main-container {
  // height: @c_height;
}

.btn {
  margin-right: 20px;
}

.tablstyle {
  padding: 15px 0;
}

.form {
  padding: 18px;
}
</style>
